import { useRef, useState } from "react";
import styles from "./index.module.less";
import { ProForm, ProFormInstance, ProFormText, ProFormRadio, ProFormSelect } from "@ant-design/pro-components";
import { Affix, Button, ConfigProvider, Flex, Space, message, Row, Col } from "antd";
import useUrl from "@/hooks/useUrl";
import { RESULT_CODES } from "@/api/helper/ResultCode";
import Loading from "@/components/Loading";
import { createJoint, updateJoint, getJointDetail, getDockList } from "@/api/modules/platform";
import { getJointTypeDict } from "@/api/modules/dict";
import { useRequest } from "ahooks";
import { useEffect } from "react";
import AMap from "@/components/AMap";
import { PageContainer } from '@ant-design/pro-layout';

export default () => {
	const formRef = useRef<ProFormInstance>();
	const { navigate, query } = useUrl();
	const detailId = query.get("detailId");
	const [detailInfo, setDetailInfo] = useState(true);
	const [location, setLocation] = useState<any>([]);

	const { loading: loadingDetail, runAsync: getDetailAsync, data: walkDetailInfo } = useRequest(getJointDetail, { manual: true });

	useEffect(() => {
		if (!detailId) return;
		getDetailAsync({ id: detailId }).then((res: any) => {
			if (res?.code === RESULT_CODES.SUCCESS) {
				const data = res?.data ?? {};
				setDetailInfo(data);
				const pointArr = data?.lonLat?.split(',')
				const InitialData = {
					...data,
					waitTimeMin: data.waitTime / 60,
					longitude: pointArr[0],
					latitude: pointArr[1],
					yaw: pointArr[2],
					notice: `${data?.notice}`,
					warning: `${data?.warning}`
				};
				setLocation([{position: pointArr}])
				formRef.current?.setFieldsValue(InitialData);
			}
		});
	}, []);

	const handleValuesChange = (changeValue: any) => {

	};

	const handleSubmit = () => {
		const values = formRef.current?.getFieldsFormatValue?.();
		const requestData = {
			...values,
			lonLat: `${values.longitude},${values.latitude},${values.yaw}`,
			waitTime: values.waitTimeMin * 60
		};
		delete requestData.longitude
		delete requestData.latitude
		delete requestData.yaw
		delete requestData.waitTimeMin
		const callback = () => {
			if(detailId) {
				updateJoint({ ...requestData, id: detailId }).then((res: any) => {
					if (res?.code === RESULT_CODES.SUCCESS) {
						message.success("更新成功");
						handleBack();
					}
				});
			} else {
				createJoint({ ...requestData }).then((res: any) => {
					if (res?.code === RESULT_CODES.SUCCESS) {
						message.success("保存成功");
						handleBack();
					}
				});
			}
		};
		formRef.current?.validateFieldsReturnFormatValue?.().then(() => {
			callback();
		});
	};


	//获取字典
	const handleGetDictList = async (code: any) => {
		const res: any = await getJointTypeDict({ parentId: 0, code })
		if (res?.code === RESULT_CODES.SUCCESS) {
			return res?.data
		}
	}

	//获取接驳点类型
	const handleGetTypeList = async () => {
		const res: any = await getJointTypeDict({ parentId: 0, code: "POINT_TYPE" })
		if (res?.code === RESULT_CODES.SUCCESS) {
			return res?.data
		}
	}

	//获取场景列表
	const handleGetDockList = async () => {
		const res: any = await getDockList({ page: { pageNum: 1, pageSize: 100 }})
		if (res?.code === RESULT_CODES.SUCCESS) {
			return res?.data?.list
		}
	}

	const handleBack = () => {
		navigate("/platform/joint");
	};

	const handleShowPoint = () => {
		const values = formRef.current?.getFieldsFormatValue?.();
		if(values.longitude && values.latitude) {
			setLocation([{position: [values.longitude, values.latitude]}])
		}
	}

	return (
		<PageContainer
			title=" "
			breadcrumb={{
				routes: [
					{ href: '/platform/joint', breadcrumbName: '接驳点管理' },
					{ href: '', breadcrumbName: detailId ? '编辑接驳点' : '新增接驳点' },
				],
			}}
		>
			<Loading isHeight100 loading={loadingDetail}>
				<div className={styles.detailContainer}>
					<div className={styles.container}>
						<ProForm
							colon={false}
							submitter={false}
							formRef={formRef}
							layout="horizontal"
							onValuesChange={handleValuesChange}
							labelCol={{ span: 6 }}
						>
							<div className={styles.content_wrap}>
								<div className={styles.content}>
									<div className={styles.moduleTitle}>{detailId ? "修改接驳点" : "新增接驳点"}</div>
									<ProFormText
										label="接驳点名称"
										name="name"
										rules={[
											{ required: true, message: "请输入接驳点名称" },
										]}
									/>
									<ProFormSelect
										label="接驳点类型"
										name="type"
										rules={[{ required: true, message: "请选择接驳点类型" }]}
										placeholder={"请选择接驳点类型"}
										request={handleGetTypeList}
									/>
									<ProFormSelect
										label="关联月台"
										name="scId"
										rules={[{ required: true, message: "请选择关联月台" }]}
										placeholder={"请选择关联月台"}
										request={handleGetDockList}
										fieldProps={{
											fieldNames: {
												label: 'scName',  // 显示文本对应的字段
												value: 'id',    // 值对应的字段
											}
										}}
									/>
									<ProForm.Item
										label="坐标"
										required
										className={styles.innerInput}
									>
										<Row gutter={8}>
											<Col span={8}>
												<ProFormText
													name="longitude"
													placeholder="经度"
													rules={[{ required: true, message: "请输入经度" }]}
													fieldProps={{
														onBlur: (e) => handleShowPoint()
													}}
												/>
											</Col>
											<Col span={8}>
												<ProFormText
													name="latitude"
													placeholder="纬度"
													rules={[{ required: true, message: "请输入纬度" }]}
													fieldProps={{
														onBlur: (e) => handleShowPoint()
													}}
												/>
											</Col>
											<Col span={8}>
												<ProFormText
													name="yaw"
													placeholder="yaw"
													rules={[{ required: true, message: "请输入yaw" }]}
													fieldProps={{
														onBlur: (e) => handleShowPoint()
													}}
												/>
											</Col>
										</Row>
									</ProForm.Item>
									<ProFormText
										label="等待时长"
										name="waitTimeMin"
										rules={[{ required: true, message: "请输入等待时长" }]}
										placeholder={"请输入等待时长"}
										fieldProps={{
											addonAfter: 'min'
										}}
									/>
									<ProFormText
										label="站点联系人"
										name="callName"
										rules={[{ required: true, message: "请输入站点联系人" }]}
										placeholder={"请输入站点联系人"}
									/>
									<ProFormText
										label="联系人电话"
										name="callPhone"
										rules={[{ required: true, message: "请输入联系人电话" }]}
										placeholder={"请输入联系人电话"}
									/>
									<ProFormRadio.Group
										label="通知状态"
										name="notice"
										rules={[{ required: true, message: "请选择通知状态" }]}
										request={() => handleGetDictList('NOTICE')}
										// options={NOTICE_STATUS_LIST}
									/>
									<ProFormRadio.Group
										label="预警状态"
										name="warning"
										rules={[{ required: true, message: "请选择预警状态" }]}
										request={() => handleGetDictList('WARNING')}
									/>
								</div>
							</div>
						</ProForm>
						<Flex justify="right" className={styles.btns}>
							<Space size={10}>
								<Button ghost type="primary" onClick={() => navigate(-1)}>
									返回
								</Button>
								<Button type="primary" onClick={handleSubmit}>
									保存
								</Button>
							</Space>
						</Flex>
					</div>
					<div className={styles.mapBox}>
						<div className={styles.moduleTitle}>地图预览</div>
						<div className={styles.mapOuter}>
							<AMap
								markers={location}
							/>
						</div>
					</div>
				</div>
			</Loading>
		</PageContainer>
	);
};
